package com.ampaiva.ui;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.os.Bundle;

import com.ampaiva.R;
import com.ampaiva.app.CustomListActivity;
import com.ampaiva.db.SQLiteAdapter;
import com.ampaiva.db.TableInfo;

public class RecordList extends CustomListActivity<String> {

    public RecordList() {
        this(R.layout.class, R.id.class);
    }

    public RecordList(Class<?> Rlayoutclass, Class<?> Ridclass) {
        super(String.class, Rlayoutclass, Ridclass);
    }

    @Override
    protected List<String> getList() {
        SQLiteAdapter db = null;
        try {
            Bundle extras = getIntent().getExtras();
            if (extras == null)
                return null;
            String tableName = "\"" + extras.getString("Table") + "\"";
            db = SQLiteAdapter.getDBAdapterInstance(this);
            db.open();
            Cursor cursor = db.selectRecordsFromDB(tableName, null, null, null, null, null, null);
            TableInfo tableInfo = db.getTableInfo(tableName);
            List<String> records = new ArrayList<String>();
            if (cursor.moveToFirst()) {
                do {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < cursor.getColumnCount(); i++) {
                        if (sb.length() > 0)
                            sb.append(" ");
                        if (tableInfo.getColumnsInfo().get(i).getType().equals("text"))
                            sb.append(cursor.getString(i));
                        else if (tableInfo.getColumnsInfo().get(i).getType().equals("integer"))
                            sb.append(cursor.getInt(i));
                        else if (tableInfo.getColumnsInfo().get(i).getType().equals("real"))
                            sb.append(cursor.getFloat(i));
                        else if (tableInfo.getColumnsInfo().get(i).getType().equals("null"))
                            sb.append("NULL");
                        else if (tableInfo.getColumnsInfo().get(i).getType().equals("blob"))
                            sb.append("BLOB");
                        else
                            sb.append("Unknown Field Type " + tableInfo.getColumnsInfo().get(i).getType());

                    }
                    records.add(sb.toString());
                } while (cursor.moveToNext());
            }
            cursor.close();
            return records;
        } finally {
            if (db != null)
                db.close();
        }
    }
}
